package cn.xuqiudong.attachment.service;

import cn.xuqiudong.attachment.model.ClientConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 描述: 配置的可用的客户端信息
 * @author Vic.xu
 * @since 2022-06-01 17:37
 */
public class ClientConfigService {

    private static final Logger logger = LoggerFactory.getLogger(ClientConfigService.class);

    /**
     * 可用客户端的 client = password
     */
    public static Map<String, String> CLIENT_MAP = new ConcurrentHashMap<>();

    private JdbcTemplate jdbcTemplate;

    public ClientConfigService(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @PostConstruct
    public void post() {
        reloadAllClient();
        logger.info("当前附件的可用客户端数量为:{}", CLIENT_MAP.size());

    }

    /**
     * 重新从数据库加载可用的客户端
     */

    public void reloadAllClient() {
        String sql = "SELECT a.id , a.client, a.password FROM client_config a WHERE a.enabled = 1 ";
        List<ClientConfig> configs = jdbcTemplate.query(sql, new BeanPropertyRowMapper<ClientConfig>(ClientConfig.class));
        CLIENT_MAP.clear();
        for (ClientConfig config : configs) {
            CLIENT_MAP.put(config.getClient(), config.getPassword());
        }
    }
}
